package com.sql.mysql.sharding.session;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.sql.mysql.sharding.config.ShardingConfigCenter;
import com.sql.mysql.sharding.reflection.ShardingReflectionHelper;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author liuzhq
 * @since 0.1
 * @Email: 837500869@qq.com
 */
@Slf4j
public class ShardingSqlSessionFactory {
	private static SqlSessionFactory sessionfactory = null;
	private static String MYBATIS_SHARDING_CONFIG_XML = "mybatis_sharding_config.xml";

	private ShardingSqlSessionFactory() {
	}

	static {
		// 先扫描注解
		try {
			log.info("开始扫描注解");
			ShardingReflectionHelper.scan();
			log.info("结束扫描注解");
			// 扫描配置文件
			InputStream inputStream = Resources.getResourceAsStream(MYBATIS_SHARDING_CONFIG_XML);
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			sessionfactory = builder.build(inputStream, ShardingConfigCenter.getAllConfig());
			log.info("succeed to build global SqlSessionFactory !");
		} catch (Exception e) {
			log.error(e.toString());
			System.exit(-1);
		} finally {
		}
	}

	// 修复为volatile变量
	public static SqlSessionFactory getSqlSessionFactory() {
		return sessionfactory;
	}
	
	public static void main(String[] args) {
		
	}

}
